package com.woniu.service.Impl.backpage;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniu.dao.backpage.AdminUserDao;
import com.woniu.dao.backpage.MenusDao;
import com.woniu.dao.backpage.WorkUserDao;
import com.woniu.entity.AdminUser;
import com.woniu.entity.Menus;
import com.woniu.entity.WorkUser;
import com.woniu.service.backpage.IAdminUserService;
import com.woniu.util.RequestParams;
import com.woniu.util.ResData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 刘海山
 * @data 2023/3/4 10:19
 */
@Service
public class AdminServiceImpl implements IAdminUserService {

    @Autowired
    private AdminUserDao adminUserDao;

    @Autowired
    private MenusDao menusDao;

    @Autowired
    private WorkUserDao workUserDao;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //查询用户名称
    @Override
    public ResData<?> findUserByUsername(String username) {
        List<AdminUser> userByUsername = adminUserDao.findUserByUsername(username);
        return new ResData<>().ok(userByUsername);
    }

    //插入一条管理员信息
    @Override
    public ResData<?> insertAdminUser(AdminUser adminUser) {
        adminUserDao.insertAdminUser(adminUser);
        return new ResData<>().ok();
    }

    //更新管理员的信息
    @Override
    public ResData<?> updateAdminUser(AdminUser adminUser) {
        adminUserDao.updateAdminUser(adminUser);
        return new ResData<>().ok();
    }

    //查询登录账号所拥有的权限
    @Override
    public ResData<?> queryMenus(String account) {
        //第一步：根据账号查redis
        String menuStr = redisTemplate.opsForValue().get("menu:" + account);
        if (menuStr!=null){
            List MenuList = JSON.parseArray(menuStr, Menus.class);
            return new ResData<>().ok(MenuList);
        }

        //先找一级菜单
        List<Menus> menus = menusDao.queryAllMenusByAccount(account);

        if (!CollectionUtils.isEmpty(menus)){
            List<Menus> parentMenus = menus.stream().filter(e -> e.getParentId() == null).collect(Collectors.toList());

            //通过一级菜单集合找到对应的二级菜单
            //第一步:先循环一级菜单，通过条件找到对应的二级菜单
            //第二步,把二级菜单放入一级菜单属性中
            for (Menus parentMenu : parentMenus) {
                List<Menus> childMenu = new ArrayList<>();
                for (Menus menu : menus) {
                    if (parentMenu.getId().equals(menu.getParentId()))
                        childMenu.add(menu);

                }
                parentMenu.setChildrenMenu(childMenu);
            }

            //反序列化
            String s = JSON.toJSONString(parentMenus);
            redisTemplate.opsForValue().set("menus:"+account,s);

            return new ResData<>().ok(parentMenus);

        }else {
            redisTemplate.opsForValue().set("menu:"+account,"");
            return new ResData<>().ok("");
        }
    }

    @Override
    public ResData<?> queryMenuTreeData(Integer userId) {
        //查询原来所有的菜单权限
        List<Menus> allMenus = menusDao.queryAllMenu();
        //查询账户下所有的权限
        List<Integer> userMenu = menusDao.queryMenuAndAuthByUserId(userId);

        //先找一级菜单,获取一级菜单的数据
        List<Menus> rootMenu = allMenus.stream().filter(e -> e.getParentId() == null).collect(Collectors.toList());

        //父级菜单找子级菜单
        rootMenu.forEach(e->{
            e.setChildrenMenu(getChildrenMenu(e.getId(),allMenus));
        });

        Map map = new HashMap();
        map.put("allMenu",rootMenu);
        map.put("userMenu",userMenu);
        return new ResData<>().ok(map);
    }

    @Override
    public ResData<?> deleteMenuByUserId(Integer userId, String menus) {
        //删除
        if(menus == null || menus.equals("")){
            menusDao.deleteUserMenuById(userId);
            return new ResData<>().ok();
        }
        
        //新增菜单权限
        String[] menu = menus.split(",");
        
        List<Integer> menuIds=new ArrayList<>();
        for (String m : menu) {
            Integer id1 = Integer.valueOf(m);
            menuIds.add(id1);
        }
        //根据用户id删除中间表的数据
        menusDao.deleteUserMenuById(userId);
        //对用户菜单权限进行插入
        menusDao.insertUserMenu(userId,menuIds);

//        for (int j = 0; j < menu.length; j++) {
//            int menuId = Integer.valueOf(menu[j]);
//            //insert语句
//            Integer result = menusDao.insertUserMenu(id, menuId);
//        }
//        Integer i = menusDao.deleteUserMenuById(id);
        return new ResData<>().ok();
    }


    //重复查找子菜单页面，父级菜单找子级菜单
    public List<Menus> getChildrenMenu(Integer id,List<Menus> menu){
        List<Menus> childrenMenus = new ArrayList<>();
        menu.forEach(e-> {
            if (id.equals(e.getParentId())) {
                childrenMenus.add(e);
            }
        });

        //递归重复父找子方法
        childrenMenus.forEach(e->{
            e.setChildrenMenu(getChildrenMenu(e.getId(),menu));
        });

        //递归结束条件
        if (CollectionUtils.isEmpty(childrenMenus)){
            return null;
        }
        return childrenMenus;
    }

    //查询后台所有的用户
    @Override
    public ResData<?> queryAllAdminUser(RequestParams<AdminUser> requestParams) {
        PageHelper.startPage(requestParams.getPageNo(),requestParams.getPageSize());
        PageInfo<AdminUser> adminUserPageInfo = new PageInfo<>(adminUserDao.queryAllAdminUser(requestParams.getData().getSearch(),requestParams.getData().getStatus()));
        return new ResData<>().ok(adminUserPageInfo);
    }

    @Override
    public ResData<?> updateAdminStatus(AdminUser adminUser) {
        if(adminUser.getStatus()==0){
            adminUser.setStatus(1);
        }else {
            adminUser.setStatus(0);
        }
        adminUserDao.updateAdminStatus(adminUser);
        return new ResData<>().ok();
    }

    //获取工作人员用户信息
    @Override
    public ResData<?> getWorkUserInfo(String account) {
        WorkUser workUserInfo = workUserDao.getWorkUserInfo(account);
        return new ResData<>().ok(workUserInfo);
    }

    //查询全部的工作人员列表展示
    @Override
    public ResData<?> queryAllWorkUser(RequestParams<WorkUser> requestParams) {
        PageHelper.startPage(requestParams.getPageNo(),requestParams.getPageSize());
        PageInfo<WorkUser> workUserPageInfo = new PageInfo<>(workUserDao.queryAllWorkUser(requestParams.getData().getSearch(),requestParams.getData().getStatus(),requestParams.getData().getState()));
        return new ResData<>().ok(workUserPageInfo);
    }

    //添加工作用户人员
    @Override
    public ResData<?> insertWorkUser(WorkUser workUser) {
        workUserDao.insertWorkUser(workUser);
        return new ResData<>().ok();
    }

    //修改工作用户人员的状态(启用或禁用)
    @Override
    public ResData<?> updateWorkUserState(WorkUser workUser) {
        if(workUser.getStatus()==0){
            workUser.setStatus(1);
        }else {
            workUser.setStatus(0);
        }
        workUserDao.updateWorkUserState(workUser);
        return new ResData<>().ok();
    }

    //修改工作人员的信息
    @Override
    public ResData<?> updateWorkUserInfo(WorkUser workUser) {
        workUserDao.updateWorkUserInfo(workUser);
        return new ResData<>().ok();
    }


}
